import { Service } from 'egg';
import { Op } from 'sequelize';

export default class RestaurantService extends Service {
  /**
   * 添加美食店申请
   */
  async addRestaurant(data: any) {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;

    // 检查店名是否已存在
    const existingRestaurant = await ctx.model.Restaurant.findOne({
      where: { 
        name: data.name,
        status: { [Op.in]: ['pending', 'approved'] }
      },
    });

    if (existingRestaurant) {
      ctx.throw(400, '店名已存在，请使用其他名称');
    }

    const restaurant = await ctx.model.Restaurant.create({
      ...data,
      user_id: userId,
      status: 'pending',
    });

    return restaurant;
  }

  /**更新美食店信息 */
  async updateRestaurant(id: number, data: any) {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;
    const restaurant = await ctx.model.Restaurant.findOne({ where: { id, user_id: userId } });
    if (!restaurant) {
      ctx.throw(400, '无权限更新美食店信息');
    }
    const result = await ctx.model.Restaurant.update(data, { where: { id } });
    return result;
  }

  /**
   * 获取美食店列表
   */
  async getRestaurantList(params: any) {
    const { ctx } = this;
    const { page = 1, page_size = 10, tag, sort, keyword, status, province_id, city_id, area_id } = params;
    const offset = (page - 1) * page_size;

    const whereCondition: any = {
      status: status || 'approved',
    };

    if(province_id) {
      whereCondition.province_id = province_id
    }
    if(city_id) {
      whereCondition.city_id = city_id
    }
    if(area_id) {
      whereCondition.area_id = area_id
    }

    // 标签筛选
    if (tag) {
      whereCondition.tags = {
        [Op.like]: `%${tag}%`,
      };
    }

    // 关键词搜索
    if (keyword) {
      whereCondition[Op.or] = [
        { name: { [Op.like]: `%${keyword}%` } },
        { description: { [Op.like]: `%${keyword}%` } },
      ];
    }

    // 排序
    let order: any = [['created_at', 'DESC']];
    if (sort === 'grade') {
      order = [['grade', 'DESC']];
    } else if (sort === 'hot') {
      // 这里可以根据评论数量或其他热度指标排序
      order = [['created_at', 'DESC']];
    }

    const { count, rows } = await ctx.model.Restaurant.findAndCountAll({
      where: whereCondition,
      order,
      limit: parseInt(page_size),
      offset,
      include: [
        {
          model: ctx.model.User,
          as: 'user',
          attributes: ['user_name'],
        },
      ],
    });

    // 处理标签数据
    const restaurants = rows.map(restaurant => {
      const restaurantData = restaurant!.toJSON() as any;
      if (restaurantData?.tags) {
        restaurantData.tagList = restaurantData?.tags.split(',').map(Number);
      }
      if(restaurantData.pictures) {
        restaurantData.imgList = restaurantData.pictures ? restaurantData.pictures.split(',').map(i => this.config.host + i) : [];
      }
      return restaurantData;
    });

    return {
      list: restaurants,
      total: count,
      page: parseInt(page),
      page_size: parseInt(page_size),
    };
  }

  /**
   * 获取美食店详情
   */
  async getRestaurantDetail(id: number) {
    const { ctx } = this;

    const restaurant = await ctx.model.Restaurant.findOne({
      where: { id, status: 'approved' },
      include: [
        {
          model: ctx.model.User,
          as: 'user',
          attributes: ['user_name'],
        },
        {
          model: ctx.model.Dish,
          as: 'dishes',
          limit: 6, // 推荐菜限制6个
        },
      ],
    });

    if (!restaurant) {
      ctx.throw(404, '美食店不存在');
    }

    const restaurantData = restaurant!.toJSON() as any;
    if (restaurantData.tags) {
      restaurantData.tagList = restaurantData.tags.split(',').map(Number);
    }

    restaurantData.imgList = restaurantData.pictures ? restaurantData.pictures.split(',').map(i => this.config.host + i) : [];

    return restaurantData;
  }

  /**
   * 收藏/取消收藏美食店
   */
  async toggleFavorite(restaurantId: number) {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;

    // 检查美食店是否存在
    const restaurant = await ctx.model.Restaurant.findOne({
      where: { id: restaurantId, status: 'approved' },
    });

    if (!restaurant) {
      ctx.throw(404, '美食店不存在');
    }

    // 检查是否已收藏
    const existFavorite = await ctx.model.Favorite.findOne({
      where: { user_id: userId, restaurant_id: restaurantId },
    });

    if (existFavorite) {
      // 取消收藏
      await existFavorite.destroy();
      return { action: 'unfavorite', message: '取消收藏成功' };
    } else {
      // 添加收藏
      await ctx.model.Favorite.create({
        user_id: userId,
        restaurant_id: restaurantId,
      });
      return { action: 'favorite', message: '收藏成功' };
    }
  }

  /**
   * 获取申请列表
   */
  async getApplicationList(params: any) {
    const { ctx } = this;
    const { page = 1, limit = 10, status, user_id } = params;
    const offset = (page - 1) * limit;

    const whereCondition: any = {};
    if (status) {
      whereCondition.status = status;
    }

    if(user_id) {
      whereCondition.user_id = user_id
    }

    const { count, rows } = await ctx.model.Restaurant.findAndCountAll({
      where: whereCondition,
      order: [['created_at', 'DESC']],
      limit: parseInt(limit),
      offset,
      include: [
        {
          model: ctx.model.User,
          as: 'user',
          attributes: ['user_name', 'mobile'],
        },
      ],
    });


    rows.forEach((it:any) => {
      it.imgList = it.pictures ? it.pictures.split(',').map(i => this.config.host + i) : [];
    });

    // 处理标签数据
    const restaurants = rows.map(restaurant => {
      const restaurantData = restaurant!.toJSON() as any;
      if (restaurantData?.tags) {
        restaurantData.tagList = restaurantData?.tags.split(',').map(Number);
      }
      if(restaurantData.pictures) {
        restaurantData.imgList = restaurantData.pictures ? restaurantData.pictures.split(',').map(i => this.config.host + i) : [];
      }
      return restaurantData;
    });

    return {
      list: restaurants,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
    };
  }

  /**
   * 管理员审核美食店
   */
  async auditRestaurant(id: number, status: 'approved' | 'rejected', audit_remark?: string) {
    const { ctx } = this;

    const restaurant = await ctx.model.Restaurant.findByPk(id);
    if (!restaurant) {
      ctx.throw(404, '申请不存在');
    }

    // 更新状态，如果有备注也可以保存
    const updateData: any = { status };
    if (audit_remark) {
      updateData.audit_remark = audit_remark;
    }

    await restaurant!.update(updateData);

    return { message: '审核完成' };
  }
}